#pragma once

#include"Util.hpp" 
#include<unordered_map>
#include<mutex>
#include<websocketpp/config/asio_no_tls.hpp>
#include<websocketpp/server.hpp>

typedef websocketpp::server<websocketpp::config::asio> wsserver_t;  
class online_manager
{
public:
    //进入大厅/房间建立连接
    void enter_game_hall(int uid,wsserver_t::connection_ptr& con)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _hall_user.insert(std::make_pair(uid,con));
    }
    void enter_game_room(int uid,wsserver_t::connection_ptr& con)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _room_user.insert(std::make_pair(uid,con));
    }
    
    //退出大厅/房间断开连接
    void exit_game_hall(int uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _hall_user.erase(uid);
    }
    void exit_game_room(int uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _room_user.erase(uid);
    }

    //是否在大厅/房间
    bool is_in_game_hall(int uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _hall_user.find(uid);
        if(it == _hall_user.end())
        {
            return false;
        }
        return true;
    }
    bool is_in_game_room(int uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _room_user.find(uid);
        if(it == _room_user.end())
        {
            return false;
        }
        return true;
    }

    //通过ID获取连接
    wsserver_t::connection_ptr get_conn_from_hall(int uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _hall_user.find(uid);
        if(it == _hall_user.end())
        {
            return  wsserver_t::connection_ptr();
        }
        return it->second;
    }
    wsserver_t::connection_ptr get_conn_from_room(int uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _room_user.find(uid);
        if(it == _room_user.end())
        {
            return  wsserver_t::connection_ptr();
        }
        return it->second;
    }

private:
    std::mutex _mutex; 
    std::unordered_map<int,wsserver_t::connection_ptr> _hall_user;
    std::unordered_map<int,wsserver_t::connection_ptr> _room_user;
};
